﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Sever
{
    class Client
    {
        private Socket clientSocket;
        private Thread t;
        public bool Connected
        {
            get
            {
                return clientSocket.Connected;
            }
        }
        private byte[] data = new byte[1024];//数据容器
        public Client(Socket client)
        {
            clientSocket = client;
            //启动一个线程，处理客户端的接受
            t = new Thread(ReceiveMsg);
            t.Start();
        }

        private void ReceiveMsg()
        {
            while (true)
            {
                //在接收数据之前，判断Socket连接是否断开
                if (!clientSocket.Connected)
                {
                    clientSocket.Close();
                    break;//跳出循环终止线程的执行
                }
                int length = clientSocket.Receive(data);
                string msg = Encoding.UTF8.GetString(data, 0, length);
                //服务端接收数据后，要将数据分发到客户端
                //广播消息
                Program.BroadcastMsg(msg);
            }
        }

        public void SendMsg(string msg)
        {
            byte[] data = Encoding.UTF8.GetBytes(msg);
            clientSocket.Send(data);
        }


    }

    class Program
    {
        static List<Client> clients = new List<Client>();
        //本机IP：192.168.100.172
        static void Main(string[] args)
        {
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            tcpServer.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9988));
            tcpServer.Listen(5000);
            Console.WriteLine("Server Running.......");
            while (true)
            {
                var clientSocket = tcpServer.Accept();
                Console.WriteLine("建立连接");
                Client client = new Client(clientSocket);
                clients.Add(client);
            }
        }

        public static void BroadcastMsg(string msg)
        {
            var noConnecteds = new List<Client>();
            foreach (var client in clients)
            {
                if (client.Connected)
                {
                    client.SendMsg(msg);
                }
                else
                {
                    noConnecteds.Add(client);
                }
            }
            foreach (var del in noConnecteds)
            {
                clients.Remove(del);
            }
        }
    }
}
